package com.shtel.paas.monitorcenter.autodiscover.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmFrequency;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmKpi;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmResponse;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmRule;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmRulesHost;
import com.shtel.paas.monitorcenter.autodiscover.entity.AlarmWhite;
import com.shtel.paas.monitorcenter.autodiscover.entity.MonitorCenterHostInfomation;
import com.shtel.paas.monitorcenter.autodiscover.entity.RuleId;
import com.shtel.paas.monitorcenter.autodiscover.mapper.AddInfoMapper;
import com.shtel.paas.monitorcenter.autodiscover.mapper.QueryInfoMapper;
import com.shtel.paas.monitorcenter.autodiscover.service.AutoDiscoverService;
import com.shtel.paas.monitorcenter.autodiscover.service.CTJson;
import com.shtel.paas.monitorcenter.autodiscover.util.AutoFind;
import com.shtel.paas.monitorcenter.autodiscover.util.HostId;

@Service
public class AutoDiscoverServiceImpl implements AutoDiscoverService {

	@Autowired
	AddInfoMapper addInfoMapper;
	@Autowired
	QueryInfoMapper queryInfoMapper;
	@Autowired
	AutoDiscoverService autoDiscoverService;
	@Autowired
	AutoFind autoFind;
	@Autowired
	HostId hostId;
	CTJson CTJson = new CTJson();

	private RestTemplate rs = new RestTemplate();

	// 保存alarm_rules_host，cpu等告警值个性化配置
	@Override
	@Transactional
	public boolean saveAlarmRulesHost(AlarmRulesHost alarmRulesHost) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveAlarmRulesHost(alarmRulesHost) > 0 ? true : false;
	}

	// 添加白名单信息
	@Override
	@Transactional
	public boolean saveAlarmWhite(AlarmWhite alarmWhite) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveAlarmWhite(alarmWhite) > 0 ? true : false;
	}

	// 添加联系人信息
	@Override
	@Transactional
	public boolean saveAlarmResponse(AlarmResponse alarmResponse) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveAlarmResponse(alarmResponse) > 0 ? true : false;
	}

	// 保存频率或者预警次数类似信息
	@Override
	@Transactional
	public boolean saveAlarmFrequency(AlarmFrequency alarmFrequency) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveAlarmFrequency(alarmFrequency) > 0 ? true : false;
	}

	// 保存运维命令
	@Override
	@Transactional
	public boolean saveAlarmKpi(AlarmKpi alarmKpi) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveAlarmKpi(alarmKpi) > 0 ? true : false;
	}

	// 保存信息
	@Override
	@Transactional
	public String saveInfo(String object) {

		Map<String, Boolean> saveResult = new HashMap<>();
		Map<String, String> errorResult = new HashMap<>();
		JSONObject JSONObject = JSON.parseObject(object);
		JSONArray ruleKpi = JSONObject.getJSONArray("rulekpi");

		if (ruleKpi.size() <= 0) {

			return "请选择需要配置的ip";

		}

		List<String> allIps = autoDiscoverService.queryALLIps();
		int num = 1;
		// 判断要保存的ip是否有存在的
		for (int i = 0; i < ruleKpi.size(); i++) {
			String ip = ruleKpi.getJSONObject(i).getString("name");
			if (allIps.contains(ip)) {
				String errorInfo = num + "、此ip已经存在";
				errorResult.put(errorInfo, ip);
				num++;
			}
		}

		if (!(errorResult.isEmpty())) {

			return errorResult.toString();

		}

		JSONArray tableRule = JSONObject.getJSONArray("tablerule");
		JSONArray contantPeople = JSONObject.getJSONArray("contantpeople");
		JSONArray freqKpi = JSONObject.getJSONArray("freqkpi");
		JSONArray modifies = JSONObject.getJSONArray("modifies");
		String updateUser = JSONObject.getString("updateUser");

		// 需要保存的频率对应的cpu-use之类的名称
		List<String> freqKpiList = new ArrayList<>();
		for (int i = 0; i < freqKpi.size(); i++) {
			String data = freqKpi.getJSONObject(i).getString("name");
			freqKpiList.add(data);
		}
		// 保存频率信息
		AlarmFrequency alarmFrequency = new AlarmFrequency();
		alarmFrequency.setTimes(JSONObject.getInteger("frecollection"));
		alarmFrequency.setMinutes(JSONObject.getInteger("frewarin"));
		boolean saveAlarmFrequencyresult = addInfoMapper.saveAlarmFrequency(alarmFrequency) > 0 ? true : false;
		saveResult.put("保存频率信息结果：", saveAlarmFrequencyresult);

		// 需要保存的运维描述以及运维命令
		for (int i = 0; i < modifies.size(); i++) {
			if (autoDiscoverService.queryKpiname(modifies.getJSONObject(i).getString("kpi_name"))) {
				AlarmKpi alarmKpi = new AlarmKpi();
				alarmKpi.setKpi_name(modifies.getJSONObject(i).getString("kpi_name"));
				alarmKpi.setKpi_desc(modifies.getJSONObject(i).getString("kpi_desc"));
				alarmKpi.setKpi_cmd(modifies.getJSONObject(i).getString("kpi_cmd"));
				boolean updateKpiResult = addInfoMapper.updateAlarmKpi(alarmKpi) > 0 ? true : false;
				String key = "更新运维命令" + i + "结果:";
				saveResult.put(key, updateKpiResult);
			} else {
				AlarmKpi alarmKpi = new AlarmKpi();
				alarmKpi.setKpi_name(modifies.getJSONObject(i).getString("kpi_name"));
				alarmKpi.setKpi_desc(modifies.getJSONObject(i).getString("kpi_desc"));
				alarmKpi.setKpi_cmd(modifies.getJSONObject(i).getString("kpi_cmd"));
				boolean saveKpiResult = addInfoMapper.saveAlarmKpi(alarmKpi) > 0 ? true : false;
				String key = "保存运维命令" + i + "结果:";
				saveResult.put(key, saveKpiResult);
			}
		}

		// tableRuleList是需要保存的个性化主机的rule
		List<AlarmRule> tableRuleList = new ArrayList<>();
		for (int i = 0; i < tableRule.size(); i++) {
			AlarmRule data = new AlarmRule();
			data.setName(tableRule.getJSONObject(i).getString("name"));
			data.setDesc(tableRule.getJSONObject(i).getString("desc"));
			data.setMin(tableRule.getJSONObject(i).getString("min"));
			data.setMax(tableRule.getJSONObject(i).getString("max"));
			data.setLevel(tableRule.getJSONObject(i).getInteger("level"));
			tableRuleList.add(data);

		}
		// defaultRule是默认的主机规则
		List<AlarmRule> defaultRule = new ArrayList<>();
		defaultRule = autoDiscoverService.queryIndexRule();

		for (int i = tableRuleList.size() - 1; i >= 0; i--) {
			for (int j = 0; j < defaultRule.size(); j++) {
				if (defaultRule.get(j).getName().equals(tableRuleList.get(i).getName())
						&& defaultRule.get(j).getDesc().equals(tableRuleList.get(i).getDesc())
						&& defaultRule.get(j).getMin().equals(tableRuleList.get(i).getMin())
						&& defaultRule.get(j).getMax().equals(tableRuleList.get(i).getMax())
						&& defaultRule.get(j).getLevel() == tableRuleList.get(i).getLevel()) {
					// tableRuleList是需要保存的个性化主机的rule
					tableRuleList.remove(i);
					break;
				}
			}
		}

		// 需要保存的主机信息
		List<String> ruleKpiList = new ArrayList<>();
		for (int i = 0; i < ruleKpi.size(); i++) {
			String data = ruleKpi.getJSONObject(i).getString("name");
			ruleKpiList.add(data);
		}
		// 保存主机信息与联系人信息与个性化主机规则
		for (String ip : ruleKpiList) {
			MonitorCenterHostInfomation monitorCenterHostInfomation = new MonitorCenterHostInfomation();
			monitorCenterHostInfomation.setIp(ip);
			boolean saveRuleKpiResult = addInfoMapper
					.saveMonitorCenterHostInfomation(monitorCenterHostInfomation)> 0 ? true : false;
			if (saveRuleKpiResult == false) {
				return ip + "主机信息保存出错";
			}
			saveResult.put(ip + "的主机信息保存结果：", saveRuleKpiResult);
			int hostId = autoDiscoverService.queryHostId(ip);

			// 保存个性化主机规则
			int ruleNum = 0;
			Timestamp timeRule = new Timestamp(System.currentTimeMillis());
			for (AlarmRule alarmRule : tableRuleList) {
				AlarmRulesHost alarmRulesHost = new AlarmRulesHost();
				alarmRulesHost.setHostid(hostId);
				alarmRulesHost.setName(alarmRule.getName());
				alarmRulesHost.setDesc(alarmRule.getDesc());
				alarmRulesHost.setMin(alarmRule.getMin());
				alarmRulesHost.setMax(alarmRule.getMax());
				alarmRulesHost.setLevel(alarmRule.getLevel());
				alarmRulesHost.setUpdateDate(timeRule);
				boolean saveRuleResult = addInfoMapper.saveAlarmRulesHost(alarmRulesHost)> 0 ? true : false;

				saveResult.put(ip + "的个性化规则" + ruleNum + "的保存结果：", saveRuleResult);
				ruleNum++;

			}

			Timestamp timeWhite = new Timestamp(System.currentTimeMillis());
			for (int i = 0; i < tableRule.size(); i++) {

				if (tableRule.getJSONObject(i).getString("rulewhite").equals("是")) {
					// 保存白名单信息
					RuleId ruleId = new RuleId();
					ruleId.setName(tableRule.getJSONObject(i).getString("name"));
					ruleId.setLevel(tableRule.getJSONObject(i).getInteger("level"));
					int ruleIdData = autoDiscoverService.queryRuleId(ruleId);

					AlarmWhite alarmWhite = new AlarmWhite();
					alarmWhite.setWhiteIp(ip);
					alarmWhite.setHostId(hostId);
					alarmWhite.setWhiteRuleId(ruleIdData);
					alarmWhite.setCreateDate(timeWhite);
					boolean saveAlarmWhiteResult = addInfoMapper.saveAlarmWhite(alarmWhite)> 0 ? true : false;
					saveResult.put(ip + "id" + ruleIdData + "保存白名单信息结果：", saveAlarmWhiteResult);
				}
			}

			// 需要保存的联系人信息
			AlarmResponse alarmResponse = new AlarmResponse();
			alarmResponse.setHostId(hostId);
			for (int i = 0; i < contantPeople.size(); i++) {
				if (contantPeople.getJSONObject(i).toString().contains("warnpeoplename")) {
					alarmResponse.setWarnContact(contantPeople.getJSONObject(i).getString("warnpeoplename"));
					alarmResponse.setWarnContype(contantPeople.getJSONObject(i).getInteger("warntype"));
					alarmResponse.setWarnPhone(contantPeople.getJSONObject(i).getString("warnphone"));
					alarmResponse.setWarnEmail(contantPeople.getJSONObject(i).getString("warnemail"));
				} else if (contantPeople.getJSONObject(i).toString().contains("dangerpeoplename")) {
					alarmResponse.setDangerContact(contantPeople.getJSONObject(i).getString("dangerpeoplename"));
					alarmResponse.setDangerContype(contantPeople.getJSONObject(i).getInteger("dangertype"));
					alarmResponse.setDangerPhone(contantPeople.getJSONObject(i).getString("dangerphone"));
					alarmResponse.setDangerEmail(contantPeople.getJSONObject(i).getString("dangeremail"));
				} else if (contantPeople.getJSONObject(i).toString().contains("seriouspeoplename")) {
					alarmResponse.setSeriousContact(contantPeople.getJSONObject(i).getString("seriouspeoplename"));
					alarmResponse.setSeriousContype(contantPeople.getJSONObject(i).getInteger("serioustype"));
					alarmResponse.setSeriousPhone(contantPeople.getJSONObject(i).getString("seriousphone"));
					alarmResponse.setSeriousEmail(contantPeople.getJSONObject(i).getString("seriousemail"));
				}
			}
			// 保存联系人信息
			boolean saveAlarmResponseResult = addInfoMapper.saveAlarmResponse(alarmResponse)> 0 ? true : false;
			saveResult.put(ip + "保存联系人信息结果：", saveAlarmResponseResult);

			autoFind.autoFindInsert(ip);

		}

		return saveResult.toString();

	}

	@Override	
	// 更新运维命令
	@Transactional
	public int updateAlarmKpi(AlarmKpi alarmKpi) {

		return addInfoMapper.updateAlarmKpi(alarmKpi);

	}

	// 保存host配置信息,即保存主机表
	@Override
	@Transactional
	public boolean saveMonitorCenterHostInfomation(MonitorCenterHostInfomation monitorCenterHostInfomation) {
		// TODO Auto-generated method stub
		return addInfoMapper.saveMonitorCenterHostInfomation(monitorCenterHostInfomation) > 0 ? true : false;
	}

	// 查询指标规则
	// public List<AlarmRule> queryIndexRule (int num){
	// Map<String, Object> returnData = new HashMap<>();
	//
	// Integer pageNum = num;
	// Integer pageSize = 5;
	// Page page = PageHelper.startPage(pageNum, pageSize, true);
	// List<AlarmRule> resultData = queryInfoMapper.queryIndexRule();
	//
	// return resultData;
	//
	// }
	// 查询指标规则
	public List<AlarmRule> queryIndexRule() {
		List<AlarmRule> data = new ArrayList<>();
		for (AlarmRule alarmRule : queryInfoMapper.queryIndexRule()) {
			if (alarmRule.getMin() == null || alarmRule.getMin().equals("")) {
				alarmRule.setMin("0");
			}

			if (alarmRule.getMax() == null || alarmRule.getMax().equals("")) {
				alarmRule.setMax("∞");
			}

			data.add(alarmRule);
		}

		return data;

	}

	// 查询频率信息
	public List<AlarmFrequency> queryFrequency() {

		return queryInfoMapper.queryFrequency();

	}

	// 查询运维命令
	// public List<AlarmKpi> queryKpi(int num){
	// Map<String, Object> returnData = new HashMap<>();
	//
	// Integer pageNum = num;
	// Integer pageSize = 5;
	// Page page = PageHelper.startPage(pageNum, pageSize, true);
	// List<AlarmKpi> resultData = queryInfoMapper.queryKpi();
	// return resultData;
	//
	// }

	public List<AlarmKpi> queryKpi() {

		return queryInfoMapper.queryKpi();

	}

	// 获取监控ip
	@Override
	public JSONObject queryIps() {
		// TODO Auto-generated method stub

		String url = "http://10.7.83.68:9091/api/v1/query?query=node_procs_running";

		String result = rs.getForObject(url, String.class);

		// String result = CTJson.make();

		JSONObject myJsonArray = JSON.parseObject(result);

		JSONObject data = myJsonArray.getJSONObject("data");
		JSONArray data2 = data.getJSONArray("result");

		List<String> jobs = new ArrayList<String>();
		for (int i = 0; i < data2.size(); i++) {
			JSONObject obj = data2.getJSONObject(i).getJSONObject("metric");
			jobs.add(obj.getString("job"));

		}

		List<String> ips = queryInfoMapper.queryHostIp();
		jobs.removeAll(ips);

		return hostId.toTree(jobs);

	}

	// 查询主机信息表里已保存的ip
	public List<String> queryALLIps() {

		return queryInfoMapper.queryHostIp();

	}

	// 根据ip查询hostId
	public int queryHostId(String ip) {

		return queryInfoMapper.queryHostId(ip);

	}

	// 查询用户对应的id
	public int queryUserId(String name) {

		return queryInfoMapper.queryUserId(name);

	}

	// 查询默认的规则的id
	public int queryRuleId(RuleId ruleId) {

		return queryInfoMapper.queryRuleId(ruleId);

	}

	// 查询kpi_name
	public boolean queryKpiname(String name) {

		return queryInfoMapper.queryKpiname(name) != null ? true : false;

	}

}
